#include "QSeeMainWin.h"
#include <QtGui/QMenu>
#include "AutoBoxLayout.h"
#include <QtGui/QTreeView>
#include <QtGui/QDirModel>
#include "AutoSplitter.h"
#include <QtCore/QDir>
#include <QtGui/QActionGroup>
#include "FileTableModel.h"
#include "FileTableDelegate.h"
#include "FileTableView.h"
#include <QtGui/QInputDialog>
#include "ImgViewWidget.h"
#include <QtGui/QApplication>
#include <QtGui/QCursor>
#include <QtGui/QActionGroup>
#include <QtGui/QMessageBox>
#include <QtGui/QContextMenuEvent>
#include <QtGui/QFileDialog>
#include <QtGui/QToolBar>
#include <QtCore/QFileInfo>
#include <QtGui/QImageReader>
#include "MobileScreen.h"
#include <QtGui/QProgressDialog>

#define APP_NAME "QSee"
#define APP_VERSION "1.22"
#define APP_TITLE APP_NAME" "APP_VERSION

QSeeMainWin::QSeeMainWin(QWidget *parent, Qt::WFlags flags)
: QMainWindow(parent, flags),
_browseModePanel(new AutoSplitter()),
_viewModePanel(new ImgViewWidget()),
_browseModeActions(new QActionGroup(this)),
_viewModeActions(new QActionGroup(this)),
_viewModeToolBar(0),_progressDialog(0)
{
	ui.setupUi(this);
	this->setWindowTitle(APP_TITLE);
	AutoBoxLayout* layout=new AutoBoxLayout();
	{
		QTreeView *treeView = new QTreeView(_browseModePanel);
		_modelDirs= new QDirModel();
		_modelDirs->setFilter(QDir::Drives|QDir::AllDirs);
		_modelDirs->setReadOnly(true);
		treeView->setModel(_modelDirs);
		treeView->setHeaderHidden(true);
		treeView->hideColumn(3);	
		treeView->hideColumn(2);	
		treeView->hideColumn(1);

		treeView->setRootIndex(_modelDirs->index(QDir::rootPath()));

		_filesView=new FileTableView(_browseModePanel);
		_modelFiles = new FileTableModel(this);
		_filesView->setModel(_modelFiles);
		_filesView->setShowGrid(true);
		_filesView->horizontalHeader()->hide();
		_filesView->verticalHeader()->hide();

		_filesView->setItemDelegate(new FileTableDelegate(_filesView));
		initFilesViewContextMenu();
		_filesView->setContextMenu(_filesViewContextMenu);


		connect (treeView,SIGNAL(activated ( const QModelIndex &)),
			this,SLOT(onDirTreeViewItemClicked(const QModelIndex &)));
		connect (treeView,SIGNAL(clicked ( const QModelIndex &)),
			this,SLOT(onDirTreeViewItemClicked(const QModelIndex &)));
		connect (_filesView,SIGNAL(scrollViewWidthChanged(int)),_modelFiles,SLOT(setScrollViewWidth(int)));
		connect (_filesView,SIGNAL(doubleClicked ( const QModelIndex & )),this,SLOT(switchToViewMode()));
		connect (_filesView,SIGNAL(currentImageFileChanged(const QString&)),_viewModePanel ,SLOT(setImageFile(const QString&)));
		layout->addWidget(_browseModePanel);
	}


	//init browser menu
	
	_actionView=ui.menuBar->addAction("View",this,SLOT(switchToViewMode()));
	_browseModeActions->addAction(_actionView);
	_browseModeActions->addAction(ui.menuBar->addAction("Resize Area",_browseModePanel,SLOT(onResizeArea())));
	_browseModeActions->addAction(ui.menuBar->addSeparator());
	QMenu* menuSorting=ui.menuBar->addMenu("&Sorting");
	{
		QAction* actionSortByName = menuSorting->addAction("By &Name",_modelFiles,SLOT(sortByName()));
		actionSortByName->setCheckable(true);
		QAction* actionSortByTime = menuSorting->addAction("By &Time",_modelFiles,SLOT(sortByTime()));
		actionSortByTime->setCheckable(true);
		QAction* actionSortBySize = menuSorting->addAction("By &Size",_modelFiles,SLOT(sortBySize()));
		actionSortBySize->setCheckable(true);
		QActionGroup* sortActionGroup=new QActionGroup(this);
		sortActionGroup->addAction(actionSortByName);
		sortActionGroup->addAction(actionSortByTime);
		sortActionGroup->addAction(actionSortBySize);
		actionSortByName->setChecked(true);
	}
	_browseModeActions->addAction(menuSorting->menuAction());
	_browseModeActions->addAction(ui.menuBar->addSeparator());

	QMenu* menuEdit=ui.menuBar->addMenu("Edit");
	{
		menuEdit->addAction("Move To",this,SLOT(onActionMoveTo()));
		menuEdit->addAction("Copy To",this,SLOT(onActionCopyTo()));
		menuEdit->addSeparator();
		menuEdit->addAction("Rename",this,SLOT(onActionRename()));
		menuEdit->addSeparator();
		menuEdit->addAction("Delete",this,SLOT(onActionDelete()));
	}
	_browseModeActions->addAction(menuEdit->menuAction());

	//_browseModeActions->addAction(ui.menuBar->addAction("&Find..."));
	_browseModeActions->addAction(ui.menuBar->addSeparator());
	QMenu* menuSetting=ui.menuBar->addMenu("&Setting");
	{
		_browseModeActions->addAction(menuSetting->addAction("Set Cell Size...",this,SLOT(onActionSetCellSize())));
		//_browseModeActions->addAction(menuSetting->addSeparator());
	}
	_browseModeActions->addAction(menuSetting->menuAction());
	_browseModeActions->addAction(ui.menuBar->addSeparator());

	_browseModeActions->addAction(ui.menuBar->addAction("&About",this,SLOT(onActionAbout())));
	_browseModeActions->addAction(ui.menuBar->addAction("E&xit",this,SLOT(close())));
	//end init browser menu


	QAction* actionPrevImg=0;
	QAction* actionNextImg=0;
	QAction* actionZoomIn=0;
	QAction* actionZoomout=0;
	QAction* actionZoomToScreen=0;
	//init view model menu
	actionPrevImg=ui.menuBar->addAction("Prev Image <=",this,SLOT(onActionGoPrev()));
	_viewModeActions->addAction(actionPrevImg);
	actionNextImg=ui.menuBar->addAction("Next Image =>",this,SLOT(onActionGoNext()));
	_viewModeActions->addAction(actionNextImg);
	_viewModeActions->addAction(ui.menuBar->addSeparator());
	QMenu* menuZoom=ui.menuBar->addMenu("&Zoom");
	{
		actionZoomIn=menuZoom->addAction("Zoom In",_viewModePanel,SLOT(zoomIn()));
		actionZoomout=menuZoom->addAction("Zoom Out",_viewModePanel,SLOT(zoomOut()));
		menuZoom->addSeparator();
		actionZoomToScreen=menuZoom->addAction("To Screen",_viewModePanel,SLOT(zoomWindowSize()));
		menuZoom->addAction("To 1:1",_viewModePanel,SLOT(zoomOriginalSize()));
	}
	_viewModeActions->addAction(menuZoom->menuAction());

	QMenu* menuRotate=ui.menuBar->addMenu("&Rotate");
	{
		menuRotate->addAction("Inhour",_viewModePanel,SLOT(rotateLeft()));
		menuRotate->addAction("Clockwise",_viewModePanel,SLOT(rotateRight()));
	}
	_viewModeActions->addAction(menuRotate->menuAction());
	_viewModeActions->addAction(ui.menuBar->addSeparator());

	QMenu* menuUseAs=ui.menuBar->addMenu("Use As");
	{
		menuUseAs->addAction("Wallpaper" ,this,SLOT(onActionUseAsWallpaper()));
		menuUseAs->addAction("Id card",this,SLOT(onActionUseAsIdCard()));
	}
	_viewModeActions->addAction(menuUseAs->menuAction());
	//_viewModeActions->addAction(ui.menuBar->addSeparator());
	//_viewModeActions->addAction(ui.menuBar->addAction("Send..."));
	_viewModeActions->addAction(ui.menuBar->addSeparator());
	_viewModeActions->addAction(ui.menuBar->addAction("Property",this,SLOT(onActionProperty())));
	_viewModeActions->addAction(ui.menuBar->addSeparator());
	_viewModeActions->addAction(ui.menuBar->addAction("&About",this,SLOT(onActionAbout())));

	_actionBack=ui.menuBar->addAction("&Back",this,SLOT(switchToBrowseMode()));
	{
	}
	_viewModeActions->addAction(_actionBack);
	//end init view mode menu 

	//init toolbar
	{
		actionPrevImg->setIcon(QIcon(":/imgs/prev.PNG"));
		actionNextImg->setIcon(QIcon(":/imgs/next.PNG"));
		actionZoomIn->setIcon(QIcon(":/imgs/ZoomIn.PNG"));
		actionZoomout->setIcon(QIcon(":/imgs/ZoomOut.PNG"));
		actionZoomToScreen->setIcon(QIcon(":/imgs/ZoomScreen.PNG"));
		_viewModeToolBar=new QToolBar("Toolbar");
		_viewModeToolBar->addAction(actionPrevImg);
		_viewModeToolBar->addAction(actionNextImg);
		_viewModeToolBar->addSeparator();
		_viewModeToolBar->addAction(actionZoomIn);
		_viewModeToolBar->addAction(actionZoomout);
		_viewModeToolBar->addSeparator();
		_viewModeToolBar->addAction(actionZoomToScreen);
		this->addToolBar(Qt::BottomToolBarArea,_viewModeToolBar);
	}
	connect (_viewModePanel,SIGNAL(leftMouseMoved()),this,SLOT(onActionGoNext()));
	connect (_viewModePanel,SIGNAL(rightMouseMoved()),this,SLOT(onActionGoPrev()));

	layout->addWidget(_viewModePanel);

	this->switchToBrowseMode();

	ui.centralWidget->setLayout(layout);
}

QSeeMainWin::~QSeeMainWin()
{
}

void QSeeMainWin::initFilesViewContextMenu(){
	_filesViewContextMenu = new QMenu();
	QAction* actionSwitchToViewMode=_filesViewContextMenu->addAction("View",this,SLOT(switchToViewMode()));
	_filesViewContextMenu->addSeparator();
	_filesViewContextMenu->addAction("Mark",this,SLOT(onActionMark()));
	_filesViewContextMenu->addAction("Unmark",this,SLOT(onActionUnmark()));
	_filesViewContextMenu->addSeparator();
	_filesViewContextMenu->addAction("Mark All",this,SLOT(onActionMarkAll()));
	_filesViewContextMenu->addAction("Clear Mark",this,SLOT(onActionClearMark()));
	//_filesViewContextMenu->addSeparator();
	//_filesViewContextMenu->addAction("Send");
	_filesViewContextMenu->addSeparator();
	_filesViewContextMenu->addAction("Property",this,SLOT(onActionProperty()));
}

void QSeeMainWin::switchToBrowseMode(){
	_viewModePanel->hide();
	_browseModePanel->show();
	_viewModeActions->setVisible(false);
	_browseModeActions->setVisible(true);
	ui.menuBar->setDefaultAction(_actionView);
	_viewModeToolBar->hide();
}

void QSeeMainWin::switchToViewMode(){
	if (!_filesView->currentIndex().isValid())
		return;

	QString currImgFile=_filesView->currentImageFile();
	if (!currImgFile.isNull()){
		_browseModePanel->hide();
		_viewModePanel->show();
		_viewModePanel->setImageFile(currImgFile);

		_viewModeActions->setVisible(true);
		_browseModeActions->setVisible(false);
		ui.menuBar->setDefaultAction(_actionBack);
		_viewModeToolBar->show();
	}
}

void QSeeMainWin::onDirTreeViewItemClicked(const QModelIndex &index){
#ifndef Q_NO_SURSOR
	QApplication::setOverrideCursor(Qt::WaitCursor);
#endif
	_modelFiles->setRootDir(_modelDirs->filePath(index));
	
#ifndef Q_NO_SURSOR
	QApplication::restoreOverrideCursor ();
#endif
}

void QSeeMainWin::onActionSetCellSize(){
	bool ok=false;
	int csize=QInputDialog::getInt(this,"QSee","Cell size",_modelFiles->filePreviewSize().width(),20,100,1,&ok);
	if (ok){
		_modelFiles->setFilePreviewSize(QSize(csize,csize));
	}
}


void QSeeMainWin::onActionGoNext(){
	_filesView->setCurrentImageToNext();

}

void QSeeMainWin::onActionGoPrev(){
	_filesView->setCurrentImageToPrev();

}

void QSeeMainWin::onActionAbout(){
	QMessageBox::about(this,"About QSee",APP_NAME" Image Browser "APP_VERSION"\n\nAuthor:Roc Xu ,Eric Zhang.\n2009.9~2009.11");
}

QStringList QSeeMainWin::selectedFiles() const{
	QStringList files=_modelFiles->signedFilesPaths();
	if (files.isEmpty()){
		QString imgFile=_filesView->currentImageFile();
		if (!imgFile.isNull())
			files<<imgFile;
	}
	return files;
}

void QSeeMainWin::onActionMoveTo(){
	QStringList imgFiles=this->selectedFiles();
	if (imgFiles.isEmpty())
		return;
	moveFilesTo(imgFiles);
	_modelFiles->unsignAll();
}

void QSeeMainWin::onActionCopyTo(){
	QStringList imgFiles=this->selectedFiles();
	if (imgFiles.isEmpty())
		return;
	copyFilesTo(imgFiles);
	_modelFiles->unsignAll();
}

void QSeeMainWin::onActionRename(){
	QString imgFile=_filesView->currentImageFile();
	if (imgFile.isEmpty())
		return;

	if (QFile::exists(imgFile)){
		QString newName=QInputDialog::getText(this,"QSee","New name:",QLineEdit::Normal,QFileInfo(imgFile).fileName());
		if (!newName.isEmpty()){
			QString newPath=QFileInfo(imgFile).absolutePath()+"/"+newName;
			if (QFile::rename(imgFile,newPath)){
				_modelFiles->notifyFileRenamed(imgFile,newPath);
			}
		}
	}
}

void QSeeMainWin::onActionDelete(){
	QStringList imgFiles=this->selectedFiles();
	if (imgFiles.isEmpty())
		return;

	QString info=(imgFiles.count()==1)?("Remove the file "+imgFiles.first()+".\nsure?"):("Remove "+QString::number(imgFiles.count())+" files.\nsure?");
	if (QMessageBox::Yes==QMessageBox::question(this,"QSee",info,QMessageBox::Yes|QMessageBox::No)){
		foreach(const QString& file,imgFiles){
			if (QFile::remove(file)){
				_modelFiles->notifyFileRemoved(file);
			}
		}
		_modelFiles->unsignAll();
	}
}


QProgressDialog* QSeeMainWin::progressDialog(const QString& label,int max){
	if (_progressDialog==0){
		_progressDialog=new QProgressDialog(this);
		_progressDialog->setWindowModality(Qt::WindowModal);
		_progressDialog->setCancelButtonText("Cancel");
	}
	_progressDialog->setLabelText(label);
	_progressDialog->setMaximum(max);
	_progressDialog->setValue(0);
	return _progressDialog;
}

void QSeeMainWin::copyFilesTo(const QStringList& files){
	QString targetDir=QFileDialog::getExistingDirectory(this,"Copy to");
	if (!targetDir.isEmpty()){
		QProgressDialog* progress=progressDialog("Copy files...", files.size());
		int val=0;
		foreach(const QString& file,files){
			if (progress->wasCanceled())
				return;
			QFile::copy(file,targetDir+"/"+QFileInfo(file).fileName());
			progress->setValue(++val);
		}
		progress->setValue(files.size());
	}
}

void QSeeMainWin::moveFilesTo(const QStringList& files){
	QString targetDir=QFileDialog::getExistingDirectory(this,"Move to");
	if (!targetDir.isEmpty()){
		QProgressDialog* progress=progressDialog("Move files...", files.size());
		int val=0;
		foreach(const QString& file,files){
			if (progress->wasCanceled())
				return;
			if (QFile::copy(file,targetDir+"/"+QFileInfo(file).fileName())){
				QFile::remove(file);
			}
			progress->setValue(++val);
		}
		progress->setValue(files.size());
	}
}

void QSeeMainWin::onActionMark(){
	_modelFiles->signItem(_filesView->currentIndex());
}

void QSeeMainWin::onActionUnmark(){
	_modelFiles->unsignItem(_filesView->currentIndex());
}

void QSeeMainWin::onActionMarkAll(){
	_modelFiles->signAll();
}

void QSeeMainWin::onActionClearMark(){
	_modelFiles->unsignAll();
}

void QSeeMainWin::onActionProperty(){
	QString imgFile=_filesView->currentImageFile();
	if (imgFile.isNull())
		return ;

	QImageReader imgReader(imgFile);
	QString info=QString("File Path: %1\nFile Size: %2KB\nImage Size: %3X%4\nImage Format: %5\n")
						.arg(imgFile)
						.arg(QFileInfo(imgFile).size()/1024)
						.arg(imgReader.size().width())
						.arg(imgReader.size().height())
						.arg(QString(imgReader.format()))
						;
	QMessageBox::information(this,"Image Property",info);
}

void QSeeMainWin::onActionUseAsWallpaper(){
	QString imgFile=_filesView->currentImageFile();
	if (imgFile.isNull())
		return ;
	static MobileScreen  ms;
	ms.setWallPaper(imgFile);
	ms.update();
}

void QSeeMainWin::onActionUseAsIdCard(){

}
